﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DH.Web.Controllers;
using DH.Entity;
using Microsoft.Extensions.DependencyInjection;
using DH.Service.Domain;
using Microsoft.AspNetCore.Authorization;
using DH.Web.Filter;
using DH.Core.Exceptions;
using DH.Core.MapperHelper;
using DH.Core;
using DH.Web.MVC.Extensions;
using DH.Service.ViewModels;
using Microsoft.Extensions.Logging;
using NLog;
using DH.Web.Attributes;

namespace DH.Web.MVC.Controllers
{
    [Authorize]
    [Route("Organize")]
    [Resource("组织架构(资源)")]
    [Guid("99a16d30-7483-4c1c-9278-f8af747a695d")]
    public class OrganizeController : SiteController<OrganizeEntity, OrganizeViewModel,string>
    {
        protected OrganizeService _orgService;
        //protected IServiceCollection _service;
        protected Microsoft.Extensions.Logging.ILogger _log;
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public OrganizeController(IServiceCollection serviceCollection,
                              OrganizeService orgService,
                              ILogger<OrganizeController> log) : base(serviceCollection, orgService)
        {
            _orgService = orgService;
            //_service = serviceCollection;

            //var logfac = _service.BuildServiceProvider().GetService<ILoggerFactory>();
            //var log = logfac.CreateLogger<OrganizeController>();
            _log = log;
        }

        
        [Route("Index")]
        [UIView("组织架构首页")]
        [Guid("fa40b65c-4ea7-4a35-928e-bfea79b43c5b")]
        public IActionResult Index()
        {
            ViewBag.CurrentUser = CurrentUserEx;
            ViewBag.CurrentViewId = "fa40b65c-4ea7-4a35-928e-bfea79b43c5b";
            return View();
        }


        [UserPermissionFilter]
        [HttpGet]
        [Route("GetModels")]
        //已弃用
        public IActionResult GetModels(string keyword, string orgParentId, int pageIndex, int pageSize)
        {
            try
            {
                PagedData<OrganizeViewModel> models;
                var page = new Pagination(pageIndex, pageSize);
                var tableEntitys = _orgService.GetOrgsByQuery(keyword, orgParentId, page);

                models = tableEntitys.ToViewModelPageData<OrganizeEntity, OrganizeViewModel>();

                //NLog如何使用
                
                Logger.Info("普通日志：获取组织列表信息");
                //log.LogInfo("获取组织信息");
                return SuccessMessage(models);

            }
            catch (Exception ex)
            {
                Logger.Error("获取组织列表发生异常：" + ex.Message);

                return InternalServerError(ex, "Error while loading {0}", nameof(OrganizeViewModel));
            }
        }

        [UserPermissionFilter]
        [HttpGet]
        [Route("GetOrgs")]
        [Function("获取组织架构列表")]
        [Guid("c7cab39f-a724-4df6-a354-7dcfb04e68e6")]
        public async Task<IActionResult> GetOrgs()
        {
            try
            {
                PagedData<OrganizeViewModel> models;
                var pagination = GetPagination();
                var queryKey = Request.Query["queryKey"][0];
                var orgId = Request.Query["treeId"][0];

                var tableEntitys = await _orgService.GetOrgsByQueryAsync(queryKey, orgId, pagination);
                models = tableEntitys.ToViewModelPageData<OrganizeEntity, OrganizeViewModel>();


                //NLog如何使用
               
                Logger.Info("普通日志：获取组织列表信息");
                _log.LogInformation("获取组织信息");
                
                var result = new { total = models.TotalCount, rows = models.DataList };
                return Json(result);

            }
            catch (Exception ex)
            {
                Logger.Error("获取组织列表发生异常：" + ex.Message);

                return InternalServerError(ex, "Error while loading {0}", nameof(OrganizeViewModel));
            }
        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("Add")]
        [Function("添加组织",isManage:true)]
        [Guid("a0e61f83-e04a-4324-960e-9740563c244f")]
        public async Task<IActionResult> Add(OrganizeViewModel input) {

            if (!ModelState.IsValid)
            {
                return ErrorMessage("实体类验证失败");
            }

            Guard.CheckArgumentNull(CrudDtoMapper, "数据转换器不能为空");
            try {

                if (!string.IsNullOrWhiteSpace(input.Id)) {

                    input.UpdatedOn = DateTimeOffset.Now;
                    input.UpdatedBy = CurrentUser.UserId;

                    await _orgService.UpdateAsync(input);
                }
                else
                {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.CreatedBy = CurrentUser.UserId;

                    await _orgService.AddAsync(input);
                    
                }

                //_orgService.UpDateSelectTreeDataList();//更新缓存
                _orgService.UpdateTreeDataList();

                return SuccessMessage("执行成功");
            }
            catch (Exception ex) {

                Logger.Error("新增组织列表发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}",nameof(OrganizeViewModel));
            }
        }


        [UserPermissionFilter]
        [HttpPost]
        [Route("Update")]
        [Function("更新组织",isManage:true)]
        [Guid("6e5788bb-588a-472c-a226-e2f3acfb6eee")]
        public async  Task<IActionResult> Update(OrganizeViewModel input)
        {
            try
            {
                input.UpdatedOn = DateTimeOffset.Now;
                input.UpdatedBy = CurrentUser.UserId;
                await _orgService.UpdateAsync(input);

                //_orgService.UpDateSelectTreeDataList();//更新缓存
                _orgService.UpdateTreeDataList();

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {


                return InternalServerError(ex, "Error while loading {0}", nameof(OrganizeViewModel));
            }
        }


        [AjaxRequestFilter]
        [HttpGet]
        [Route("CheckSortId")]
        [Function("检查组织排序号是否已存在")]
        [Guid("d1cbb940-50fb-42de-95f7-5c43001f5c38")]
        public IActionResult CheckExistSortId(string parentId,int sortIndex,string Id)
        {
            var res= _orgService.CheckExistSortIndex(parentId,sortIndex,Id);
            if (!res)
            {
                return SuccessMessage(new{ res=true});
            }
            else
            {
                return SuccessMessage(new { res=false},"已存在排序号，保存后会影响已存在排序号，请保存或者选择其他排序号");
            }
            
        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("Delete")]
        [Function("删除组织",isManage:true)]
        [Guid("572b9547-a2ec-4555-bec0-e115205165ca")]
        public async Task<IActionResult> Delete(string[] ids)
        {
            try {

                await _orgService.DeleteAsync(ids);

                //_orgService.UpDateSelectTreeDataList();//更新缓存
                _orgService.UpdateTreeDataList();

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                return InternalServerError(ex, "Error while loading {0}", nameof(OrganizeViewModel));
            }
        }

        //定义ajax 请求 过滤器
        [AjaxRequestFilter]
        [HttpGet]
        [Route("SelectTreeData")]
        ///已弃用
        ///
        public IActionResult GetSelectTreeData(string id)
        {
            var treeSelects = new List<TreeSelectViewModel>();
            treeSelects = _orgService.GetSelectTreeDataList();

            //var firstNode = new TreeSelectViewModel()
            //{
            //    id = "00000000-0000-0000-0000-000000000000",
            //    text = "根节点"
            //};
            //if (!treeSelects.Any(c=>c.id== "00000000-0000-0000-0000-000000000000"))
            //{
            //    treeSelects.Insert(0, firstNode);
            //}
            
            //return SuccessMessage(treeSelects,"");
            return new JsonResult(treeSelects);
        }

        [AjaxRequestFilter]
        [HttpPost]
        [Route("ComboTreeData")]
        [Function("获取组织树(后台组织成树结构)")]
        [Guid("764fb96d-ce5e-4759-9435-83efcb823147")]
        ///<summary>
        ///后台返回结构就是已经组成的一个根节点的树
        ///</summary>
        public IActionResult GetComboTreeData()
        {
            var treeSelects = new List<TreeSelectViewModel>();
            treeSelects = _orgService.GetSelectTreeDataList();
            
            return new JsonResult(treeSelects);
        }

        [AjaxRequestFilter]
        [HttpGet]
        [Route("TreeData")]
        [Function("获取组织树")]
        [Guid("2d7a814e-51cc-49ab-a599-cbde825d8078")]
        /// <summary>
        /// 后台返回数据列表(有ParentId),依靠Ztree组织成树
        /// </summary>
        public async Task<IActionResult> GetTreeData()
        {
            var trees = new List<TreeSelectViewModel>();
            //trees = _orgService.GetTreeDataList(); //获取组织架构
            trees =await _orgService.GetCacheTreeDataListAsync();//获取缓存组织架构



            return new JsonResult(trees);
        }
    }
}